import os
import fastapi_cdn_host
from fastapi import FastAPI
from dotenv import load_dotenv
from tortoise.contrib.fastapi import register_tortoise
from . import settings
from .apps.common.views import app as common_app
from .apps.users.views import app as user_app
from .apps.chat.views import app as chat_app
from .utils import middleware
from .utils import exceptions
from .utils import redis_tools


def create_app() -> FastAPI:
    load_dotenv()
    app = FastAPI(
        title=os.environ.get('APP_NAME'),
        summary=os.environ.get('APP_SUMMARY'),
        description=os.environ.get('APP_DESCRIPTION'),
        version=os.environ.get('APP_VERSION'),
        exception_handlers={
            exceptions.HTTPException: exceptions.global_http_exception_handler,
            exceptions.RequestValidationError: exceptions.global_request_exception_handler,
        },
    )
    fastapi_cdn_host.patch_docs(app)

    register_tortoise(
        app,
        config=settings.TORTOISE_ORM,
        generate_schemas=False,
        add_exception_handlers=True

    )
    redis_tools.register_redis(
        app,
        config=settings.REDIS
    )

    app.include_router(common_app)
    app.include_router(user_app, prefix='/user')
    app.include_router(chat_app, prefix='/chat')

    http_middleware = app.middleware('http')
    http_middleware(middleware.log_requests)

    return app